package com.huaboot.system.strategy.impl;
import com.huaboot.commont.exception.BusinessException;
import com.huaboot.system.entity.SysObjectStoreEntity;
import com.huaboot.system.enums.UploadModeEnum;
import com.huaboot.system.service.SysObjectStoreService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.StatObjectArgs;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


/**
 * description: Minio存储实现
 * date: 2023/10/7 15:04
 * author: ff
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class MinioUploadStrategyImpl extends AbstractUploadStrategyImpl {
    private final SysObjectStoreService objectStoreService;
    private SysObjectStoreEntity objectStore;

    private MinioClient minioClient;


    @Override
    public void initClient() throws Exception {
        objectStore = objectStoreService.getObjectStoreByLabel(UploadModeEnum.Minio_UPLOAD.getMode());
        minioClient = MinioClient.builder().endpoint(objectStore.getEndpoint())
                .credentials(objectStore.getAccessKey(),objectStore.getAccessKeySecret()).build();
        log.info("Local minio Init Success...");
    }

    @Override
    public boolean checkFileIsExisted(String fileRelativePath, String fileName) throws Exception{
        boolean exist = true;
        try {
            minioClient
                    .statObject(StatObjectArgs.builder().bucket(objectStore.getBucket()).object(fileRelativePath+fileName).build());
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }

    @Override
    public void executeUpload(MultipartFile file, String fileRelativePath, String fileName)  {
        log.info("File Upload Starts...");
        try {
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(objectStore.getBucket())
                    .object(fileRelativePath+fileName)
                    .stream(file.getInputStream(), file.getInputStream().available(), -1)
                    .contentType(file.getContentType())
                    .build()
            );
        }catch (Exception e){
            throw new BusinessException("存储桶不存在，请检查配置后重新测试！");
        }
        log.info("File Upload Finish...");
    }

    @Override
    public String getPublicNetworkAccessUrl(String fileRelativePath, String fileName) {
        return objectStore.getDomainUrl() +"/"+ fileRelativePath + fileName;
    }
}
